<template>
  <div class="app-container">

    <div class="search-container">
      <div class="search-title">
        查询条件
      </div>
      <div class="search-form">
        <div class="form-row">
          <div class="form-column">
            <span class="column-title">文件名称</span>
            <el-input v-model="queryParams.keyword" placeholder="请输入" class="input-w150" clearable
              @keyup.enter.native="handleQuery" />
          </div>
          <div class="form-column">
            <span class="column-title">文档类型</span>
            <el-select v-model="queryParams.materialType" placeholder="请选择" class="input-w150" clearable filterable>
              <el-option v-for="dict in dict.type.sys_file_type" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </div>
          <!-- <div class="form-column">
            <span class="column-title">文件来源</span>
            <el-select v-model="queryParams.sourceId" placeholder="请选择" class="input-w150" clearable filterable>
              <el-option v-for="dict in dict.type.sys_position_type" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </div> -->
          <div class="form-column">
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          </div>
        </div>
      </div>
    </div>


    <div class="body-container">
      <div class="operation-bar">
        <div class="bar-title">
          资料列表
        </div>
        <div class="bar-btn__wrapper" v-if="isEdit">
          <div class="bar-btn" @click="handleAdd"><i class="el-icon-plus"></i>新增</div>
        </div>
      </div>

      <el-tabs class="cus-tabs" type="card" v-model="tabActive" @tab-click="handleTabClick">
        <el-tab-pane v-for="item in dict.type.sys_material_type" :key="item.value" :label="item.label"
          :name="item.value"></el-tab-pane>
      </el-tabs>

      <el-table v-loading="loading" stripe :data="dataList">
        <el-table-column type="index" label="#" align="center" min-width="100"></el-table-column>
        <el-table-column label="文件" prop="materialName" align="left" min-width="200">
          <template slot-scope="scope">
            <div class="file-name">
              <img src="./../../assets/images/word.png" v-if="scope.row.materialType == '0'" class="img-icon">
              <img src="./../../assets/images/excel.png" v-if="scope.row.materialType == '1'" class="img-icon">
              <img src="./../../assets/images/ppt.png" v-if="scope.row.materialType == '2'" class="img-icon">
              <img src="./../../assets/images/img.png" v-if="scope.row.materialType == '3'" class="img-icon">
              <img src="./../../assets/images/pdf.png" v-if="scope.row.materialType == '4'" class="img-icon">
              <img src="./../../assets/images/zip.png" v-if="scope.row.materialType == '5'" class="img-icon">
              <img src="./../../assets/images/video.png" v-if="scope.row.materialType == '6'" class="img-icon">
              <span>{{ scope.row.materialName }}</span>
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column label="更新时间" prop="updateTime" align="center" min-width="170" /> -->
        <el-table-column label="简介" prop="materialDesc" align="center" min-width="120" show-overflow-tooltip
          width="150" />
        <el-table-column label="上传者" prop="uploadUser" align="center" min-width="100" />
        <el-table-column label="上传者单位" prop="unitCode" align="center" min-width="100" >
            <template slot-scope="scope">
                {{ getDeptName(scope.row.unitCode) }}
              </template>
          </el-table-column>
        <el-table-column label="下载次数" prop="downloadTimes" align="center" min-width="100" />
        <el-table-column label="操作" align="center" min-width="120" class-name="small-padding fixed-width">
          <div class="table-option" slot-scope="scope" v-if="scope.row.roleId !== 1">
            <span @click="handleDownload(scope.row)">下载</span>
            <span @click="handleEdit(scope.row)" v-if="isEdit">编辑</span>
            <span class="danger" @click="handleDelete(scope.row)" v-if="isEdit">删除</span>
          </div>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>

    <Edit :title="editTitle" :materialCategoryType="tabActive" :editType="editType" :editData="editData"
      :visible.sync="editDialog" @close="getList"></Edit>

  </div>
</template>

<script>
import { getDeptName } from "@/utils/ruoyi";
import { materialList, materialDel, materialDownload } from "@/api/file";
import Edit from './components/edit.vue'
import store from '@/store';

export default {
  name: "file",
  dicts: ['sys_file_type', 'sys_position_type', 'sys_material_type'],
  components: {
    Edit
  },
  data () {
    return {
      tabActive: '0',
      dataList: [],
      loading: true,
      editType: 'add',
      editData: {},
      total: 0,
      editTitle: "",
      editDialog: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sourceId: undefined,
        keyword: undefined,
        materialType: undefined,
        materialCategoryType: '0'
      },
      form: {}
    };
  },
  computed:{
    isEdit(){
      return this.$auth.hasRoleOr(["admin", "ordinary"]);
    },
     downloadUrl () {
      return process.env.VUE_APP_DOWNLOAD_URL
    },
      deptList () {
        return this.$store.state.user.deptList
    },
  },
  created () {
    console.log(this.$store.state.user.userInfo.deptId)
    this.getList();
  },
  methods: {
    getDeptName (id) {
      return getDeptName(this.deptList, id)
    },
    async xhrequest (url, callback) {
      let DownUrl = url;
      let data = await fetch(DownUrl)
        .then((response) => response.blob())
        .then((res) => {
          //获取文件格式
          var index = DownUrl.lastIndexOf(".");
          //获取文件后缀判断文件格式
          var fileType = DownUrl.substr(index + 1);
          let blod = new Blob([res]);
          if (typeof callback == "function") {
            callback(blod, fileType)
          }
        });
      return data;
    },
     downloadBlob (blob, fileName)  {
      try {
        const href = window.URL.createObjectURL(blob); //创建下载的链接
        if (window.navigator.msSaveBlob) {
          window.navigator.msSaveBlob(blob, fileName);
        } else {
          // 谷歌浏览器 创建a标签 新增download属性下载
          const downloadElement = document.createElement("a");
          downloadElement.href = href;
          downloadElement.target = "_blank";
          downloadElement.download = fileName;
          document.body.appendChild(downloadElement);
          downloadElement.click(); // 点击下载
          document.body.removeChild(downloadElement); // 下载完成移除元素
          window.URL.revokeObjectURL(href); // 释放掉blob对象
        }
      } catch (e) {
        console.log("下载失败");
      }
    },
    async handleDownload (item) {
      const res = await materialDownload(item.id)
      let _this=this
      this.xhrequest(this.downloadUrl+item.uploadUrl,
        function (blob, type) {
          _this.downloadBlob(blob, item.materialName)
        }
      )
    },
    // tab点击
    handleTabClick (tab, event) {
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10
      this.getList()
    },
    // 查询
    async getList () {
      this.loading = true;
      this.queryParams.materialCategoryType = this.tabActive
      const res = await materialList(this.queryParams)
      this.loading = false;
      if (res.code === 200) {
        this.dataList = res.rows || [];
        this.total = res.total || 0;
      } else {
        this.dataList = [];
        this.total = 0;
      }
    },
    // 查询
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置
    resetQuery () {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        sourceId: undefined,
        keyword: undefined,
        materialType: undefined,
        materialCategoryType: 0
      }
      this.handleQuery();
    },
    // 新增
    handleAdd () {
      this.editTitle = "新增资料";
      this.editType = 'add'
      this.editDialog = true;
    },
    // 编辑
    handleEdit (row) {
      this.editTitle = "编辑资料";
      this.editType = 'edit'
      this.editData = row
      this.editDialog = true;
    },
    // 删除
    handleDelete (row) {
      this.$modal.confirm('是否确认删除?').then(function () {
        return materialDel(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    }
  }
};
</script>
<style lang="scss" scoped>
.file-name {
  display: flex;
  align-items: center;
  justify-content: flex-start;

  .img-icon {
    width: 20px;
    height: 20px;
  }

  span {
    margin-left: 8px;
  }
}
</style>